<template>
  <div class="cart-page">
    <el-header class="header" height="70px">
      <div class="header-content">
        <div class="logo">
          <h1 @click="$router.push('/')" style="cursor: pointer;">周周淘商城</h1>
        </div>
        <div class="nav-actions">
          <el-button @click="$router.push('/products')" type="primary" plain>
            继续购物
          </el-button>
          <template v-if="userStore.token">
            <el-dropdown @command="handleUserCommand">
              <el-button type="primary">
                {{ userStore.userInfo?.username || '用户' }}
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </div>
      </div>
    </el-header>

    <el-main class="main-content">
      <div class="page-header">
        <h2>购物车</h2>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="$router.push('/')">首页</el-breadcrumb-item>
          <el-breadcrumb-item>购物车</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div v-if="cartItems.length > 0" class="cart-content">
        <el-table :data="cartItems" style="width: 100%" v-loading="loading">
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品" width="400">
            <template #default="{ row }">
              <div class="product-info">
                <img :src="row.image" :alt="row.name" class="product-image">
                <div class="product-details">
                  <h3>{{ row.name }}</h3>
                  <p v-if="row.spec && row.spec !== '{}' && row.spec.trim() !== ''" class="product-spec">{{ row.spec }}</p>
                  <p>库存: {{ row.stock }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ formatPrice(row.price) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="150">
            <template #default="{ row }">
              <el-input-number
                  v-model="row.num"
                  :min="1"
                  :max="row.stock"
                  @change="updateQuantity(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              <span class="subtotal">¥{{ formatPrice(row.price * row.num) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="removeItem(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-footer">
          <div class="cart-summary">
            <p>共 {{ totalItems }} 件商品</p>
            <p class="total-price">总计：¥{{ formatPrice(totalPrice) }}</p>
          </div>
          <div class="cart-actions">
            <el-button @click="clearCart">清空购物车</el-button>
            <el-button type="primary" size="large" @click="checkout">
              结算 ({{ totalItems }})
            </el-button>
          </div>
        </div>
      </div>

      <div v-else class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="$router.push('/products')">
            去购物
          </el-button>
        </el-empty>
      </div>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { queryMyCarts, updateCartItem, deleteCartItem, deleteCartItemByIds } from '@/api/cart'
import type { CartVO, Cart } from '@/api/cart'

const router = useRouter()
const userStore = useUserStore()

// 购物车数据
const cartItems = ref<CartVO[]>([])
const loading = ref(false)

const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.num, 0)
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.num), 0)
})

// 格式化价格（将分转换为元）
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2)
}

const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/')
      break
  }
}

const updateQuantity = async (item: CartVO) => {
  try {
    // 创建一个可修改的 Cart 对象
    const cartToUpdate: Cart = {
      id: item.id,
      userId: item.userId,
      itemId: item.itemId,
      name: item.name,
      image: item.image,
      price: item.price,
      num: item.num,
      stock: item.stock
    };
    await updateCartItem(cartToUpdate);
    ElMessage.success('数量已更新');
  } catch (error) {
    console.error('更新数量失败:', error);
    ElMessage.error('更新数量失败');
  }
}

const removeItem = async (item: CartVO) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteCartItem(item.id);
    ElMessage.success('商品已删除');
    loadCartItems(); // 重新加载购物车数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error);
      ElMessage.error('删除商品失败');
    }
  }
}

const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const itemIds = cartItems.value.map(item => item.id);
    if (itemIds.length > 0) {
      await deleteCartItemByIds(itemIds);
    }
    ElMessage.success('购物车已清空');
    cartItems.value = []; // 清空本地数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空购物车失败:', error);
      ElMessage.error('清空购物车失败');
    }
  }
}

const checkout = () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算');
    return;
  }

  // 跳转到订单页面进行结算
  router.push('/orders?from=cart');
}

// 加载购物车数据
const loadCartItems = async () => {
  try {
    loading.value = true;
    const response = await queryMyCarts();
    console.log('购物车API响应:', response); // 调试日志

    const responseData = response.data

    // 检查是否是新的API格式（包含code字段）
    if (responseData && responseData.code !== undefined) {
      // 新格式：{code: 200, msg: "OK", data: [...]}
      if (responseData.code === 200 && responseData.data) {
        cartItems.value = responseData.data || []
      } else {
        console.error('购物车数据格式错误:', responseData)
        ElMessage.error(responseData.msg || '购物车数据格式错误')
      }
    } else if (responseData && Array.isArray(responseData)) {
      // 旧格式：直接返回数组
      cartItems.value = responseData
    } else {
      console.error('购物车数据格式错误:', responseData)
      ElMessage.error('购物车数据格式错误')
    }
  } catch (error) {
    console.error('加载购物车数据失败:', error)
    ElMessage.error('加载购物车数据失败')
  } finally {
    loading.value = false
  }
};

// 生命周期钩子
onMounted(() => {
  // 检查用户是否已登录
  if (!userStore.token) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }

  loadCartItems();
});
</script>

<style scoped>
.cart-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo h1 {
  color: #409eff;
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.cart-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-details h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.product-details p {
  margin: 0 0 3px 0;
  color: #666;
  font-size: 14px;
}

.product-spec {
  color: #999;
  font-size: 12px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.cart-summary p {
  margin: 5px 0;
  color: #666;
}

.total-price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
}

.cart-actions {
  display: flex;
  gap: 15px;
}

.empty-cart {
  background: #fff;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
